package com.DGT.OCRCAjuntosCorreo.Utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.swing.Spring;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;



public class UtilsOCR {

	 private static Connection conn;

	private static Properties propPaths;

	private static Logger logger= Logger.getLogger(UtilsOCR.class.getName());

	public static void loadProperties(){
         propPaths = new Properties();
         InputStream is = null;
         
 		try {
 			is=new FileInputStream(new File("paths.properties").getPath());
 			//is=new FileInputStream(UtilsOCR.class.getResource("paths.properties").getPath());		//<<<obtener ruta del properties
 			
 			propPaths.load(is);
 			is.close();
 		}catch(IOException ioe) {
 			logger.error(ioe.getMessage());
 			ioe.printStackTrace();
 		}
	 }
	 
	 public static Properties getPropertiesPaths(){
		 if(propPaths==null){
			 loadProperties();
		 }
		 return propPaths;
	 }
	 
	 /**
		 * Move sourceFile to destinationFile
		 * @param sourceFile
		 * @param destinationFile
		 */
		 public static boolean fileMove(String sourceFile, String destinationFile) {
			 boolean moved=false;
			 File source = new File(sourceFile);
			 File outFile = new File(destinationFile);
			 if(source.exists()&&!outFile.exists()) {
				 try { 
	            	 if(source.getName().length()>50){
	            		 File newFileSource =renameFile(source);
	            		 File newFileDest=renameFile(outFile);
	            		 logger.info("El archivo "+source.getName()+" tiene un nombre demasiado largo, sera renombrado como "+newFileSource.getName());
	            		 FileUtils.moveFile(newFileSource, newFileDest);
	            		 logger.info("Movido fichero" + newFileSource+" en " +newFileDest);
	            	 }
	            	 else{ 
	            		 FileUtils.moveFile(source, outFile);
	            		 logger.info("Movido fichero" + sourceFile+" en " + destinationFile+System.getProperty("line.separator"));
	            	 }
	            		 moved=true;
				} catch (IOException e) {
					 logger.error("No ha sido posible Mover "+sourceFile+ "a la carpeta: "+destinationFile+" "+e.getMessage());
				}
			 }

			return moved;	
		}
		 
		 //--------------------------------------------
		 
		 public static boolean fileCopy(String sourceFile, String destinationFile) {
			 boolean moved=false;
			 File source = new File(sourceFile);
			 File outFile = new File(destinationFile);
			 if(source.exists()&&!outFile.exists()) {
			             try {
			            	 if(source.getName().length()>50){
			            		 File newFileSource =renameFile(source);
			            		 File newFileDest=renameFile(outFile);
			            		 logger.info("El archivo "+source.getName()+" tiene un nombre demasiado largo, sera renombrado como "+newFileSource.getName());
			            		 FileUtils.copyFile(newFileSource, newFileDest);
			            		 logger.info("copiado fichero" + newFileSource+" en " +newFileDest);
			            	 }
			            	 else{ 
			            		 FileUtils.copyFile(source, outFile);
			            		 logger.info("copiado fichero" + sourceFile+" en " + destinationFile+System.getProperty("line.separator"));
			            	 }
			            		 moved=true;
						} catch (IOException e) {
							 logger.error("No ha sido posible copiar "+sourceFile+ "a la carpeta: "+destinationFile+" "+e.getMessage());
						}
			 }

			return moved;	
		}
		 
		 //--------------------------------------------
		 
		public static Connection connectionOracleGestDocsBBDD() throws SQLException {
		//  DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
			try {
				Class.forName("oracle.jdbc.driver.OracleDriver");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			if(conn==null){
				String ipServidorBBDD=UtilsOCR.getPropertiesPaths().getProperty("IPSERVIDORBBDD");
				String puerto=UtilsOCR.getPropertiesPaths().getProperty("PUERTO");
				String usuario=UtilsOCR.getPropertiesPaths().getProperty("USUARIO");
				String password=UtilsOCR.getPropertiesPaths().getProperty("PASSWORD");
				String esquemaBBDD=UtilsOCR.getPropertiesPaths().getProperty("ESQUEMABBDD");
				DriverManager.setLoginTimeout(0); 
				conn = DriverManager.getConnection("jdbc:oracle:thin:"+ipServidorBBDD+":"+puerto+":"+esquemaBBDD, usuario, password);
				Statement s=conn.createStatement();    
				s.execute("select 1 from dual");    
				s.close();
			}
			else if(conn.isClosed()){
				conn=null;
				conn=connectionOracleGestDocsBBDD();
			}
		    return conn;
		}
		public static void closeConnection() {
//			try {
//				conn.close();
//			} catch (SQLException e) {
//				e.printStackTrace();
//			}
		}
		
		@SuppressWarnings("null")
		public static String[] filtrar(String path){
			int c=0;
			String[] file=null;
			File directorio = new File(path);
			String[] archivos= directorio.list();
			
			for(String archivo:archivos){
				if(archivo.endsWith(".inttemp")){
					file[c]=archivo;
					c++;
				}
			}
			
			return file;
		}
		
		public static File renameFile(File source) throws IOException{
			 String newName= source.getName().substring(source.getName().length()-50,source.getName().length());
    		 String newPath=source.getAbsolutePath().replace(source.getName(), newName);
    		 File newFile=new File(newPath);
    		     		
    		 if(source.exists()){
    			 FileUtils.moveFile(source, newFile);
    		 }
    		 
    		 return newFile;
		}
		
		public static String ranameBigNamedDocument(String oldName){
			String newName="";
			newName=oldName.substring(oldName.length()-50, oldName.length());
			return newName;
		}

}

